package com.xstudio.pvzreborn.block.entity;

import com.mojang.datafixers.DSL;
import com.xstudio.pvzreborn.PVZReborn;
import com.xstudio.pvzreborn.block.BlockManager;
import com.xstudio.pvzreborn.block.BlockNames;
import net.minecraft.world.level.block.entity.BlockEntity;
import net.minecraft.world.level.block.entity.BlockEntityType;
import net.minecraftforge.eventbus.api.IEventBus;
import net.minecraftforge.registries.DeferredRegister;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.registries.RegistryObject;

import java.util.HashMap;
import java.util.Map;

public class BlockEntityManager {

	public static final Map<String, RegistryObject<? extends BlockEntityType<?>>> BLOCK_ENTITY_TYPES = new HashMap<>();
	private static final DeferredRegister<BlockEntityType<?>> BLOCK_ENTITY_TYPE_REGISTRY = DeferredRegister.create(ForgeRegistries.BLOCK_ENTITIES, PVZReborn.MOD_ID);

	public static void init(IEventBus bus) {
        PVZReborn.LOGGER.info("Initializing block entities");
        BLOCK_ENTITY_TYPE_REGISTRY.register(bus);
        registerBlockEntityType(BlockNames.SEED_PACKET_CREATOR, BlockEntitySeedPacketCreator::new);
        registerBlockEntityType(BlockNames.POLAR_CRAFTING_TABLE, BlockEntityPolarCraftingTable::new);
        PVZReborn.LOGGER.info("Initialized block entities");
    }

    public static <T extends BlockEntity> void registerBlockEntityType(String name, BlockEntityType.BlockEntitySupplier<T> factory) {
	    RegistryObject<BlockEntityType<T>> type = BLOCK_ENTITY_TYPE_REGISTRY.register(name, () -> BlockEntityType.Builder.of(factory, BlockManager.getBlock(name)).build(DSL.remainderType()));
        BLOCK_ENTITY_TYPES.put(name, type);
    }

    @SuppressWarnings("unchecked")
    public static <T extends BlockEntity> BlockEntityType<T> getBlockEntityType(String name) {
        return (BlockEntityType<T>) BLOCK_ENTITY_TYPES.get(name).get();
    }

}

